package com.lzy.securityResources.service.impl;

import com.lzy.system.organization.entity.SysRole;
import com.lzy.system.organization.entity.security.entity.SecurityRole;
import com.lzy.system.organization.entity.security.entity.SecurityUser;
import com.lzy.system.organization.service.ISysUserService;
import com.lzy.system.organization.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * description: SecurityUserImpl (定义security数据库获取用户角色信息)<br>
 * date: 2022-8-15 16:36 <br>
 * author: lcc <br>
 * version: 1.0 <br>
 */
@Component(value = "securityUser")
public class SecurityUserImpl implements UserDetailsService {

    ISysUserService iSysUserService;

    @Autowired
    public SecurityUserImpl(ISysUserService iSysUserService) {
        this.iSysUserService = iSysUserService;
    }

    @Override
    public SecurityUser loadUserByUsername(String username) throws UsernameNotFoundException {
        SecurityUser securityUser = null;
        try {
            SysUserVo sysUser = iSysUserService.getUserByUserId(username);
            if (sysUser == null) {
                throw new UsernameNotFoundException("用户或者密码错误！");
            }
            if (sysUser.getStatus() != 1) {
                throw new UsernameNotFoundException("用户被锁定！");
            }
            List<SecurityRole> securityRoles = new ArrayList<>();
            for (SysRole role : sysUser.getRoles()) {
                SecurityRole securityRole = new SecurityRole();
                securityRole.setAuthority("ROLE_"+role.getRole_name());
                securityRoles.add(securityRole);
            }

            securityUser = new SecurityUser();
            securityUser.setId(sysUser.getId());
            securityUser.setName(sysUser.getNickname());
            securityUser.setUsername(sysUser.getUsername());
            securityUser.setPassword(sysUser.getPassword());
            securityUser.setAuthorities(securityRoles);
            securityUser.setEnabled(sysUser.getStatus()==1);
            securityUser.setAccountNonExpired(true);
            securityUser.setAccountNonLocked(true);
            securityUser.setCredentialsNonExpired(true);
        } catch (Exception e) {
            throw new UsernameNotFoundException("用户或者密码错误！");
        }
        return securityUser;
    }
}
